rm(list=ls(all=TRUE))  # new
load("dta.Rdata")

dta = data.list$dta
members = data.list$members

# members matrix
trim <- function (x) gsub("^\\s+|\\s+$", "", x)
make.members.matrix <- function(){
	
	members2 = strsplit(members,split="[.]")
	for (i in 1:length(members2)){
		m = members2[[i]]
		mname = trim(paste(m[5:length(m)],collapse="."))
		members2[[i]] = c(m[1:4],mname)
	}
	t(matrix(unlist(members2),nrow=5))
}
members.mat = make.members.matrix()
colnames(members.mat)=c("type","cong","id","party","name")


# the borders over congresses

borders = rep(NA, times = 24)
i = match("H",members.mat[,1])
borders [1]=i
for (q in 1:(length(borders)/2) ){
#browser()	
	j = match("S", members.mat[-(1:i),1])
	h = i+j
	borders[2*q]=h 
	k = match("H", members.mat[-(1:h),1])
	i = h+k
	borders[2*q+1]=i
}
borders = borders[1:24]

# count # of votes for each bill in each congress

count.mat = array(NA, dim = c(24, dim(dta)[2], 2))

for (i in 1:dim(count.mat)[1]){
	if (i < length(borders)){
	temp.bloc = dta[(borders[i]:(borders[i+1]-1) ),]
	count.mat [i,,1]= colSums( (temp.bloc>0), na.rm =TRUE ) # Yay
	count.mat [i,,2]= colSums( (temp.bloc==0), na.rm =TRUE ) # Nay


	} else if (i==length(borders)){
	temp.bloc = dta[(borders[i]:dim(dta)[1]),]
	count.mat [i,,1]= colSums( (temp.bloc>0), na.rm =TRUE ) # Yay
	count.mat [i,,2]= colSums( (temp.bloc==0), na.rm =TRUE ) # Nay
	}
} 

temp.yay = colSums( (count.mat[,,1]>0) )
ind.bridge = (temp.yay>1)
bridge.count.mat = count.mat [ ,ind.bridge,]


total.yay = colSums(bridge.count.mat[,,1])
total.nay = colSums(bridge.count.mat[,,2])


temp= total.nay/(total.yay + total.nay)


####
# figure 3
#######

hist(temp,freq=FALSE, main="", xlab="Proportion of Nay votes in bridge votes/decisions" )


######
# figure 4
######
load("results.Rdata")
ideal.est = results[[1]]

item.disc = ideal.est$betabar[,1]
hist(item.disc)


bridge.beta = item.disc[ind.bridge]
temp=1-ind.bridge
nonbridge.beta = item.disc[as.logical(temp)]

par(mfrow=c(1,2),pty='s')
hist(bridge.beta,freq=FALSE,xlim=c(-15,15), main="Bridge votes/decisions", xlab="Item discrimination parameters" )
hist(nonbridge.beta,freq=FALSE,xlim=c(-15,15), main="Nonbridging roll call votes", xlab="Item discrimination parameters" )
